package com.book.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;

import java.io.IOException;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description:http连接工具类
 * @date 2023/10/30 20:44
 */
public class HttpClientUtils {
    public static JSONObject execute(String url, HttpMethod httpMethod){
        HttpRequestBase httpRequest = null;
        try{
            HttpClient client = HttpClients.createDefault();
            if(httpMethod == HttpMethod.GET){
                httpRequest = new HttpGet(url);
            }else{
                httpRequest = new HttpPost(url);
            }
            HttpEntity entity = client.execute(httpRequest).getEntity();
            return JSONObject.parseObject(EntityUtils.toString(entity));
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            httpRequest.releaseConnection();
        }

        return null;
    }


}
